﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Threading;
using QQ;
using System.Text.RegularExpressions;
using System.Runtime.Serialization.Json;

namespace QQHelper
{
    public class HttpHelper
    {
        #region 登录
        /// <summary>
        /// 获取字符流
        /// </summary>
        /// <param name="url"></param>
        /// <param name="cookieContainer"></param>
        /// <returns></returns>
        public static Stream GetStream(string url, CookieContainer cookieContainer)
        {
            HttpWebRequest httpWebRequest = null;
            HttpWebResponse httpWebResponse = null;

            try
            {
                httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                httpWebRequest.CookieContainer = cookieContainer;
                //httpWebRequest.ContentType = contentType;
                //httpWebRequest.Referer = referer;
                //httpWebRequest.Accept = accept;
                //httpWebRequest.UserAgent = userAgent;
                httpWebRequest.Method = "GET";
                httpWebRequest.ServicePoint.ConnectionLimit = int.MaxValue;
                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream responseStream = httpWebResponse.GetResponseStream();
                return responseStream;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public static List<Cookie> GetCookies(string url, CookieContainer cookieContainer)
        {
            List<Cookie> cookies = new List<Cookie>();
            CookieCollection cc = cookieContainer.GetCookies(new Uri(url));
            foreach (Cookie item in cc)
            {
                cookies.Add(item);
            }
            return cookies;
        }

        /// <summary>
        /// 获取HTML
        /// </summary>
        /// <param name="url"></param>
        /// <param name="cookieContainer"></param>
        /// <returns></returns>
        public static string GetHtml(string url, CookieContainer cookieContainer)
        {
            Thread.Sleep(1000);
            HttpWebRequest httpWebRequest = null;
            HttpWebResponse httpWebResponse = null;
            try
            {
                httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                httpWebRequest.CookieContainer = cookieContainer;
                httpWebRequest.ServicePoint.ConnectionLimit = int.MaxValue;
                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream responseStream = httpWebResponse.GetResponseStream();
                StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
                string html = streamReader.ReadToEnd();
                streamReader.Close();
                responseStream.Close();
                httpWebRequest.Abort();
                httpWebResponse.Close();
                return html;
            }
            catch (Exception)
            {
                return string.Empty;
            }

        }


        /// <summary>
        /// 取验证码
        /// </summary>
        /// <param name="qqnum"></param>
        /// <param name="cookie"></param>
        /// <returns></returns>
        public static string GetVerfiyCode(string qqnum, CookieContainer cookie)
        {
            Random rand = new Random();
            double r = rand.NextDouble();
            string checkcodeurl = string.Format(@"http://check.ptlogin2.qq.com/check?uin={0}&appid=1006102&r={1}", qqnum, r);
            Stream stream = HttpHelper.GetStream(checkcodeurl, cookie);
            StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);
            return streamReader.ReadToEnd();
        }
        //取图片验证码,可将验证码直接输出在image中
        public static Stream GetVerfycodeImage(CookieContainer cookie, string qqnum)
        {
            Random rand = new Random();
            double r = rand.NextDouble();
            string codeimageurl = string.Format("http://captcha.qq.com/getimage?aid=1006102&r={0}&uin={1}", r, qqnum);
            return HttpHelper.GetStream(codeimageurl, cookie);
        }
        /// <summary>
        /// 登录是否成功
        /// </summary>
        /// <param name="qqnum">qq号码</param>
        /// <param name="code">验证码</param>
        /// <param name="passwords">密码</param>
        /// <param name="cookie"></param>
        /// <returns></returns>
        public static bool IsLogin(string qqnum, string code, string passwords, CookieContainer cookie)
        {
            string password = QQMd5.Encrypt(qqnum, passwords, code);
            string loginUrlstring = @"http://ptlogin2.qq.com/login?u=" + qqnum + "&p=" + password + "&verifycode=" + code + "&aid=1006102&u1=http%3A%2F%2Fid.qq.com%2Findex.html&h=1&ptredirect=1&ptlang=2052&from_ui=1&dumy=&fp=loginerroralert&action=8-29-82478035&mibao_css=&t=1&g=1";
            Stream stream = HttpHelper.GetStream(loginUrlstring, cookie);
            StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);
            string retString = streamReader.ReadToEnd();//        retString    "ptuiCB('0','0','http://id.qq.com/index.html','1','登录成功！', 'xxx');\r\n"    string
            bool b = retString.Contains("ptuiCB('0',");
            if (b != true)
            {
                if (retString.Contains(("ptuiCB('4',")))
                    throw new Exception(retString.Substring(23, 17));
                return false;
            }
            return true;
        }
        /// <summary>
        /// 获取qq个人空间主页
        /// </summary>
        /// <param name="qqnum"></param>
        /// <param name="cookie"></param>
        /// <returns></returns>
        public static string GetQQZoneMainContent(string qqnum, CookieContainer cookie)
        {
            string loginUrlstring = @"http://user.qzone.qq.com/" + qqnum;
            Stream stream = HttpHelper.GetStream(loginUrlstring, cookie);
            StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);
            string retString = streamReader.ReadToEnd();
            return retString;
        }

        public static string GetQQZoneRelatedOwerInfo(string qqnum, CookieContainer cookie)
        {
            List<Cookie> cc = GetCookies(@"http://user.qzone.qq.com/" + qqnum, cookie);
            Cookie ck = cc.Find(delegate(Cookie c) { return c.Name == "skey"; });
            string sk = ck.Value.ToString();
            int gtk = GetG_TK(sk);
            string loginUrlstring = string.Format(@"http://ic2.s8.qzone.qq.com/cgi-bin/feeds/feeds2_html_pav_all?uin={0}&useutf8=1&g_tk={1}", qqnum, gtk);
            Stream stream = HttpHelper.GetStream(loginUrlstring, cookie);
            StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);

            string retString = streamReader.ReadToEnd();
            return retString;
        }

        /// <summary>
        /// 与我相关
        /// </summary>
        /// <param name="p"></param>
        /// <param name="cookie"></param>
        /// <returns></returns>
        public static string GetContentALL(string p, CookieContainer cookie)
        {

            List<Cookie> cc = GetCookies(@"http://user.qzone.qq.com/" + p, cookie);
            Cookie ck = cc.Find(delegate(Cookie c) { return c.Name == "skey"; });
            string sk = ck.Value.ToString();
            int gtk = GetG_TK(sk);
            string loginUrlstring = string.Format(@"http://ic2.s8.qzone.qq.com/cgi-bin/feeds/feeds2_html_pav_all?uin={0}&useutf8=1&g_tk={1}", p, gtk);
            Stream stream = HttpHelper.GetStream(loginUrlstring, cookie);
            StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);

            string retString = streamReader.ReadToEnd();
            return retString;
        }

        /// <summary>
        /// 根据Skey获取 G_TK
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int GetG_TK(string str)
        {
            int hash = 5381;
            for (int i = 0; i < str.Length; i++)
            {
                hash += (hash << 5) + str[i];
            }
            return hash & 0x7fffffff;
        }
        /// <summary>
        /// 获取GTK 
        /// </summary>
        /// <param name="url">Null时 默认为http://user.qzone.qq.com/</param>
        /// <param name="qqNum"></param>
        /// <param name="cookie"></param>
        /// <returns></returns>
        public static int GetG_TK(string url, string qqNum, CookieContainer cookie)
        {
            if (url == null)
                url = @"http://user.qzone.qq.com/";
            List<Cookie> cc = HttpHelper.GetCookies(url + qqNum, cookie);
            Cookie ck = cc.Find(delegate(Cookie c) { return c.Name == "skey"; });
            string sk = ck.Value.ToString();
            int gtk = HttpHelper.GetG_TK(sk);
            return gtk;
        }
        #endregion
        private static string GetUrlInfo(string urlstr, CookieContainer cookie)
        {

            Stream stream = GetStream(urlstr, cookie);
            StreamReader streamReader = new StreamReader(stream, Encoding.UTF8);
            string retString = streamReader.ReadToEnd();
            return retString;
        }
        #region QQ群
        /// <summary>
        /// 获取qq群信息
        /// </summary>
        /// <param name="qqNum"></param>
        /// <param name="gtk"></param>
        /// <param name="cookie"></param>
        public static string GetQQqunJson(string qqNum, int gtk, CookieContainer cookie)
        {
            string url = @"http://qun.qzone.qq.com/cgi-bin/get_group_list?uin={0}&g_tk={1}";
            string urlstr = string.Format(url, qqNum, gtk);
            return GetUrlInfo(urlstr, cookie);
        }
        /// <summary>
        /// 获取qq群人员信息
        /// </summary>
        /// <param name="qqNum"></param>
        /// <param name="groupid"></param>
        /// <param name="gtk"></param>
        /// <param name="cookie"></param>
        /// <returns></returns>
        public static string GetQQMember(string qqNum, string groupid, int gtk, CookieContainer cookie)
        {
            string url = @"http://qun.qzone.qq.com/cgi-bin/get_group_member?uin={0}&groupid={1}&g_tk={2}";
            string urlstr = string.Format(url, qqNum, groupid, gtk);
            return GetUrlInfo(urlstr, cookie);
        }

        #endregion

    }

}
